package com.example.handheld4_gsignal_app.services;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.example.handheld4_gsignal_app.data.SignalData;
import com.example.handheld4_gsignal_app.network.ApiClient;
import com.example.handheld4_gsignal_app.data.models.SignalCollectionRequest;
import com.example.handheld4_gsignal_app.data.models.SignalCollectionResponse;
import com.google.gson.Gson;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.TimeZone;

/**
 * 信号服务类 - 处理信号采集相关功能
 */
public class SignalService {
    
    private static final String TAG = "SignalService";
    
    private Context context;
    private Handler handler;
    private Runnable signalUpdateRunnable;
    private boolean isCollecting = false;
    private SignalCallback callback;
    private Gson gson;
    private Random random;
    private ApiClient apiClient;

    public interface SignalCallback {
        void onSignalUpdate(int strength, String location, String network);
        void onError(String error);
    }

    public interface ReportCallback {
        void onReportSuccess();
        void onReportError(String error);
    }

    public SignalService(Context context) {
        this.context = context;
        this.handler = new Handler(Looper.getMainLooper());
        this.random = new Random();
        this.apiClient = ApiClient.getInstance(context);
        this.gson = new Gson();
    }

    /**
     * 开始信号采集
     */
    public void startCollection(SignalCallback callback) {
        this.callback = callback;
        this.isCollecting = true;
        
        // 开始定期更新信号数据
        signalUpdateRunnable = new Runnable() {
            @Override
            public void run() {
                if (isCollecting) {
                    updateSignalData();
                    handler.postDelayed(this, 2000); // 每2秒更新一次
                }
            }
        };
        
        handler.post(signalUpdateRunnable);
    }

    /**
     * 停止信号采集
     */
    public void stopCollection() {
        isCollecting = false;
        if (signalUpdateRunnable != null) {
            handler.removeCallbacks(signalUpdateRunnable);
        }
    }

    /**
     * 更新信号数据
     */
    private void updateSignalData() {
        try {
            // 模拟信号强度 (-150 到 -50 dBm)
            int signalStrength = -150 + random.nextInt(100);
            
            // 获取位置信息
            String location = getLocationInfo();
            
            // 获取网络信息
            String network = getNetworkInfo();
            
            if (callback != null) {
                callback.onSignalUpdate(signalStrength, location, network);
            }
        } catch (Exception e) {
            if (callback != null) {
                callback.onError("信号采集错误: " + e.getMessage());
            }
        }
    }

    /**
     * 获取位置信息
     */
    private String getLocationInfo() {
        // 模拟GPS坐标 (北京地区)
        double latitude = 39.9042 + (random.nextDouble() - 0.5) * 0.1;
        double longitude = 116.4074 + (random.nextDouble() - 0.5) * 0.1;
        return String.format(Locale.getDefault(), "%.4f, %.4f", latitude, longitude);
    }

    /**
     * 获取网络信息
     */
    private String getNetworkInfo() {
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (telephonyManager != null) {
                String operatorName = telephonyManager.getNetworkOperatorName();
                if (operatorName == null || operatorName.isEmpty()) {
                    operatorName = "未知运营商";
                } else {
                    // 确保字符编码正确
//                    try {
//                        // 重新编码确保中文字符正确显示
//                        byte[] bytes = operatorName.getBytes("ISO-8859-1");
//                        operatorName = new String(bytes, "UTF-8");
//                    } catch (Exception e) {
//                        // 如果编码转换失败，使用原始字符串
//                    }
                }
                return "4G - " + operatorName;
            }
        } catch (Exception e) {
            // 忽略权限错误
        }
        return "4G - 模拟网络";
    }

    /**
     * 获取当前时间戳 (ISO 8601格式)
     */
    private String getCurrentTimestamp() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        return sdf.format(new Date());
    }

    /**
     * 上报数据
     */
    public void reportData(ReportCallback callback) {
        try {
            // 创建当前信号数据
            SignalData signalData = createSignalData();
            
            // 转换为API请求格式
            SignalCollectionRequest request = convertToApiRequest(signalData);
            
            // 调用真实的数据上报API
            String requestJson = gson.toJson(request);
            apiClient.post("/api/signals", requestJson, new ApiClient.ApiCallback() {
                @Override
                public void onSuccess(String response) {
                    try {
                        // 解析响应
                        SignalCollectionResponse responseObj = gson.fromJson(response, SignalCollectionResponse.class);
                        
                        // 保存到本地数据库
                        saveToLocalDatabase(signalData);
                        
                        if (callback != null) {
                            callback.onReportSuccess();
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "解析上报响应失败", e);
                        if (callback != null) {
                            callback.onReportError("解析响应失败: " + e.getMessage());
                        }
                    }
                }
                
                @Override
                public void onError(String error) {
                    if (callback != null) {
                        callback.onReportError(error);
                    }
                }
            });
        } catch (Exception e) {
            if (callback != null) {
                callback.onReportError("上报失败: " + e.getMessage());
            }
        }
    }

    /**
     * 将SignalData转换为API请求格式
     */
    private SignalCollectionRequest convertToApiRequest(SignalData signalData) {
        SignalCollectionRequest request = new SignalCollectionRequest();
        request.setDeviceId(signalData.getDeviceId());
        request.setSignalStrength(signalData.getSignalStrength());
        request.setLatitude(signalData.getLatitude());
        request.setLongitude(signalData.getLongitude());
        request.setAltitude(signalData.getAltitude());
        request.setAccuracy(new Double(signalData.getAccuracy()));
        request.setNetworkType(signalData.getNetworkType());
        request.setOperatorName(signalData.getOperatorName());
        request.setCellId(signalData.getCellId());
        request.setLac(signalData.getLac());
        request.setMcc(signalData.getMcc());
        request.setMnc(signalData.getMnc());
        request.setRsrp(signalData.getRsrp());
        request.setRsrq(signalData.getRsrq());
        request.setRssi(signalData.getRssi());
        request.setSnr(signalData.getSnr());
        request.setCollectedAt(signalData.getCollectedAt());
        request.setCreatedAt(signalData.getCollectedAt());
        request.setUploadedAt(signalData.getCollectedAt());
        return request;
    }

    /**
     * 保存数据到本地数据库
     */
    private void saveToLocalDatabase(SignalData signalData) {
        // 这里可以调用数据库服务保存数据
        // 暂时只记录日志
        android.util.Log.d("SignalService", "数据已保存到本地数据库: " + signalData.getCollectedAt());
    }

    /**
     * 创建信号数据对象
     */
    public SignalData createSignalData() {
        SignalData signalData = new SignalData();
        signalData.setDeviceId("DEVICE_001");
        signalData.setSignalStrength(-150 + random.nextInt(100));
        signalData.setLatitude(39.9042 + (random.nextDouble() - 0.5) * 0.1);
        signalData.setLongitude(116.4074 + (random.nextDouble() - 0.5) * 0.1);
        signalData.setAltitude(50.0 + random.nextDouble() * 100);
        signalData.setAccuracy(5.0f + random.nextFloat() * 10);
        signalData.setNetworkType("4G");
        signalData.setOperatorName("中国移动");
        signalData.setCellId("12345");
        signalData.setLac("67890");
        signalData.setMcc("460");
        signalData.setMnc("00");
        signalData.setRsrp(-90 + random.nextInt(20));
        signalData.setRsrq(-10.5 + random.nextDouble() * 5);
        signalData.setRssi(-80 + random.nextInt(15));
        signalData.setSnr(15.2 + random.nextDouble() * 10);
        signalData.setCollectedAt(getCurrentTimestamp());
        
        return signalData;
    }
}